import { Inject, Provide } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { SectEntity } from '@entity/jx3/sect.entity';
import { ListSectDTO, CreateSectDTO, UpdateSectDTO } from '@dto/jx3/sect.dto';
import { resBuild } from '@utils/resBuild';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { getOperator, getTimeFormat, getUUID } from '@utils';

@Provide()
export class SectService {
  @Inject()
  ctx: Context;

  @InjectEntityModel(SectEntity)
  SectEntity: Repository<SectEntity>;

  // 列表
  async list(queryParams: ListSectDTO) {
    const queryBuilder = this.SectEntity.createQueryBuilder('entity');

    // 添加按创建时间排序，默认降序（最新的在前）
    queryBuilder.orderBy('entity.createTime', 'DESC');

    if (queryParams.pageNum && queryParams.pageSize) {
      queryBuilder
        .skip((queryParams.pageNum - 1) * queryParams.pageSize)
        .take(queryParams.pageSize);
    }

    const [rows, total] = await queryBuilder.getManyAndCount();
    return resBuild.list(rows, total);
  }

  // 添加
  async create(Sect: CreateSectDTO) {
    // 新增
    Sect.id = getUUID();
    const myEntity = this.SectEntity.create(Sect);
    myEntity.setCreateBy(getOperator(this.ctx));
    myEntity.setUpdateBy(getOperator(this.ctx));
    myEntity.setCreateTime(getTimeFormat());
    myEntity.setUpdateTime(getTimeFormat());
    await this.SectEntity.save(myEntity);
    return resBuild.success();
  }

  // 删除
  async delete(id: string) {
    const ids = id.split(',').map(id => Number(id));
    await this.SectEntity.delete(ids);
    return resBuild.success();
  }

  // 修改
  async update(Sect: UpdateSectDTO) {
    const myEntity = this.SectEntity.create(Sect);
    myEntity.setUpdateBy(getOperator(this.ctx));
    myEntity.setUpdateTime(getTimeFormat());
    await this.SectEntity.save(myEntity);
    return resBuild.success();
  }

  // 详情
  async detail(id: string) {
    const detailInfo = await this.SectEntity.findOneBy({
      id,
    });
    return resBuild.data(detailInfo);
  }
}
